from django.shortcuts import render,redirect

from sm_system.views import COOKIE_NAME
from sm_system.models import *
from django.http import HttpResponse
# Create your views here.


# 分部功能
def index(request):

    supermarket_id = str(request.COOKIES.get(COOKIE_NAME))[0:4]
    contracts = ContractInfo.objects.filter(supermarket_id=supermarket_id)
    context = {"contracts": contracts}
    return render(request, 'contract/contract.html', context)


def update(request, id):

    contract = ContractInfo.objects.get(id=id)
    context = {"contract": contract}
    return render(request, 'contract/contractUpdate.html', context)


def update_form(request):

    if request.POST:
        id = request.POST['id']
        contract = ContractInfo.objects.get(id=id)
        contract.supermarket_id = request.POST['supermarket_id']
        contract.supplier_id = request.POST['supplier_id']
        contract.content = request.POST['content']
        contract.save()

    return redirect('/juniorAdmin/contract_info/')


def add(request):

    return render(request, 'contract/contractAdd.html')


def add_form(request):
    if request.POST:
        contract = ContractInfo()
        contract.id = request.POST['id']
        contract.supermarket_id = request.POST['supermarket_id']
        contract.supplier_id = request.POST['supplier_id']
        contract.content = request.POST['content']
        contract.save()

    return redirect('/juniorAdmin/contract_info/')


def delete(request, id):

    contract = ContractInfo.objects.get(id=id)
    contract.delete()
    return redirect('/juniorAdmin/contract_info/')

